package com.tourscool.springboot.starter.utils;

import org.springframework.boot.SpringApplication;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Cedric
 * @date 2022/07/06 17:34
 * @description 资源配置工具类
 */
public class PropertySourcesUtil {

    private static final String NAME = "aop.yinfeng";

    private static ConfigurableEnvironment environment;
    private static SpringApplication application;

    public static void setEnvironment(ConfigurableEnvironment environment) {
        if (PropertySourcesUtil.environment == null) {
            PropertySourcesUtil.environment = environment;
        }
    }

    public static SpringApplication getApplication() {
        return application;
    }

    public static void setApplication(SpringApplication application) {
        PropertySourcesUtil.application = application;
    }

    public static void set(String key, Object value) {
        getSourceMap().put(key, value);
    }

    public static Object get(String key) {
        return getSourceMap().get(key);
    }

    public static Map<String, Object> getSourceMap() {
        PropertySource<?> propertySource = environment.getPropertySources().get(NAME);
        Map<String, Object> source;
        if (propertySource == null) {
            source = new LinkedHashMap<String, Object>();
            propertySource = new MapPropertySource(NAME, source);
            environment.getPropertySources().addLast(propertySource);
        }
        source = (Map<String, Object>) propertySource.getSource();
        return source;
    }

}
